<?php
/**
 * 
 * 用户注册接口
 * @author alang
 *
 */

class Api_register_mdl extends Base_Controller
{
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function outputdata($data)
	{
		
		if (!empty( $data['USERNAME'] )  && !empty($data['EMAIL'])  && !empty( $data['PASSWORD'] )) {
			
			$result = $this->_checkEmail($data['EMAIL']);
			
			if ( $result ) {
				
				$outputdata['TAG'] = $data['TAG'];
				$outputdata['STATUS'] = 1;
				$outputdata['ERRORMESSAGE'] = 'haved';
				//$outputdata['USERINFO'] = null;
				
			} else {
				
				$passwd = Common::do_hash($data['PASSWORD']);
				$user['txpassword'] = $passwd;
				$user['txemail'] = $data['EMAIL'];
				$user['txusername'] = $data['USERNAME'];
				$user['activecode'] = $this->_getActiveCode();
				$user['createtime'] = time();
				$flag = $this->_addUser($user);
				
				if( $flag ) {
					//注册成功
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 0;
					$outputdata['ERRORMESSAGE'] = $user['activecode'];
					//发验证码邮件
					$this->_email( '',$data['EMAIL'],$user['activecode'] );
					//登录
					/*
					$this->load->library('auth');
					$user['uid'] = $flag;
					
					$token = $this->auth->process_login($user);
					$userinfo['TOKEN'] = $token;
					$userinfo['EMAIL'] = $data['EMAIL'];
					$userinfo['USERID'] = (int)$flag;
					$userinfo['LASTLOGIN'] = date('Y-m-d H:i:s',$user['createtime']);
					$userinfo['GOLD'] = 0;
					$userinfo['USERNAME'] = $data['USERNAME'];
					
					$outputdata['USERINFO'] = $userinfo;
					*/
					
					
				} else {
					
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 1;
					$outputdata['ERRORMESSAGE'] = 'system error';
					//$outputdata['USERINFO'] = null;
				}
			}
			
		} else {
			
			$outputdata['TAG'] = $data['TAG'];
			$outputdata['STATUS'] = 1;
			$outputdata['ERRORMESSAGE'] = 'info empty';
			//$outputdata['USERINFO'] = null;
					
		}
		
		header('Content-Type:text/html; charset=utf-8', false);
		echo json_encode($outputdata);
	}
	
	/**
	 * 
	 * 判断邮箱是否存在
	 * @param String $email
	 */
	private function _checkEmail( $email )
	{
		$this->load->helper('email'); 
		if ( valid_email( $email ) ) {
			
			return $this->db->select('*')->from( 'cj_users' )->where('txemail', $email)->count_all_results();
			
		} else {
			return 1;
		}
	}
	
	
	/**
	 * 
	 * 添加用户
	 * @param Array $user
	 */
	private function _addUser($user)
	{
		$this->db->insert('cj_users',$user);
		return ($this->db->affected_rows() > 0) ? $this->db->insert_id() : FALSE;
	}
	
	
	/**
	 * 产生激活码
	 */
	
	private function _getActiveCode()
	{
		$str = '1234567890abcdefghijklmnopqrsduvwxyz';
		$len = strlen($str);
		$randnum = '';
		
		for ($i = 0; $i < 6; $i++) { 
			$start = rand(1,strlen($str) - 1); 
			$randnum .= substr($str,$start,1); 
		} 
		
		return $randnum;
		
	}
	
	/**
	 * 
	 * 发送邮件
	 * @param String $form
	 * @param Sting $to
	 * @param String $body
	 */
	private function _email( $form,$to,$body )
	{
		
			$this->load->library('phpmailer');
			try {
				$this->phpmailer->IsSMTP();                           // tell the class to use SMTP
				$this->phpmailer->SMTPAuth   = true;                  // enable SMTP authentication
				$this->phpmailer->Port       = 25;                    // set the SMTP server port
				$this->phpmailer->Host       = "smtp.163.com"; // SMTP server
				$this->phpmailer->Username   = "lottery2013888@163.com";     // SMTP server username
				$this->phpmailer->Password   = "lottery2013";            // SMTP server password
			
				$this->phpmailer->IsSendmail();  // tell the class to use Sendmail
			
				$this->phpmailer->AddReplyTo($to,"First Last");
			
				$this->phpmailer->From       = "lottery2013888@163.com";
				$this->phpmailer->FromName   = "lottery";
	
				$this->phpmailer->AddAddress($to);
			
				$this->phpmailer->Subject  = "First PHPMailer Message";
			
				$this->phpmailer->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
				$this->phpmailer->WordWrap   = 80; // set word wrap
			
				$this->phpmailer->MsgHTML($body);
			
				$this->phpmailer->IsHTML(true); // send as HTML
			
				$this->phpmailer->Send();
				
				/*-------------------------*/
				$fp = fopen('email.txt','a+');
				fwrite($fp,$to.': '.date("Y-m-d H:i:s")."\r\n");
				fclose($fp);
				/*-------------------------*/
				return true;
			} catch ( phpmailerException $e ){
				
				return false;
				
			}
		

	}
}